package org.destinyshine.cricket.connector.aoi;

import org.destinyshine.cricket.connector.Connector;
import org.destinyshine.cricket.connector.nio.SocketChannelConnectionHandler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * async server socket，nio2的连接器。
 *
 * @author destinyliu
 */
public class AsyncSocketChannelConnector implements Connector {

    @Override
    public void connect() throws IOException {
        int cores = Runtime.getRuntime().availableProcessors();
        ExecutorService thredPool = Executors.newCachedThreadPool();
        AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup.withCachedThreadPool(thredPool, cores * 2);
        AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();
        serverSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
            @Override
            public void completed(AsynchronousSocketChannel socketChannel, Void attachment) {
                serverSocketChannel.accept(null, this);

                // socketChannel.setOption()
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                //TODO :: ??
                socketChannel.read(buffer, new SocketChannelConnectionHandler(null, null), new CompletionHandler<Integer, SocketChannelConnectionHandler>() {
                    @Override
                    public void completed(Integer result, SocketChannelConnectionHandler attachment) {
                        if (result != -1) {
                            attachment.resolveByteBuffer(buffer);
                        }
                    }

                    @Override
                    public void failed(Throwable exc, SocketChannelConnectionHandler attachment) {

                    }
                });
            }

            @Override
            public void failed(Throwable exc, Void attachment) {

            }
        });
    }

    @Override
    public void disconnect() {

    }

}
